package readFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-06-16
 * Time: 11:47
 */
public class ReadMain {

    /*
    * 使用InputStreamReader去读取*/

    public static void main(String[] args) {
        String filePath = "test1.txt";
        try(FileInputStream fis = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8)
        ){
            char[] bytes = new char[1024];//每次读取1024个字节

            StringBuilder builder = new StringBuilder();
//            int readLength;
//            while((readLength = isr.read(bytes) ) != -1){
//                builder.append(bytes,0,readLength);
//            }
            while(isr.read(bytes) != -1){
                builder.append(bytes);
            }

            String str = builder.toString();
            System.out.println(str);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /*
    * 因为不知道文件的具体长度，所以我们创建出来的字节数组会有空的情况，所以打印出来的结果就会由乱码*/
    public static void main1(String[] args) {

        String filePath = "test1.txt";
        try(FileInputStream fis = new FileInputStream(filePath)){
            byte[] bytes = new byte[1024];//用一个字节数组来接收
            fis.read(bytes);

            String string = new String(bytes);
            System.out.println("读取到的内容是" + string);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
